﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using blackhouse.WebNemo.Business.Groups;

namespace blackhouse.WebNemo.Business.AutomaticInstalation {
    public class NemoInstalator {

        #region Fields

        //        private readonly Factory factory;
        private readonly GroupCollection groups;
        private readonly string path;
        private readonly IEnumerable<GroupConfiguration> groupConfigurations;

        #endregion

        #region Constructors

        public NemoInstalator(string pathToConfigurationFilesAreLocated) {
            this.path = pathToConfigurationFilesAreLocated;
            var factory = Factory.Instance();
            this.groups = factory.GetGroups();
            var files = this.GetAllConfigurationFiles();

            this.groupConfigurations = (
                            from @group in this.groups
                            let groupFile = files.FirstOrDefault(fi => fi.Name.EndsWith(@group.SystemName + ".xml"))
                            select
                            ((groupFile == null) ?
                            new GroupConfiguration(@group, pathToConfigurationFilesAreLocated) :
                            new GroupConfiguration(@group, groupFile))
                            );
        }

        #endregion

        #region Methods

        private IEnumerable<FileInfo> GetAllConfigurationFiles() {
            var directory = new DirectoryInfo(this.path);
            if (!directory.Exists)
                directory.Create();
            return directory.GetFiles("*.xml");
        }

        /// <summary>
        /// check and create, if necessary, local configuration file for each group
        /// </summary>
        public void EnsureLocalConfigurationFiles() {
            foreach (var groupConfiguration in this.groupConfigurations.Where(groupConfiguration => !groupConfiguration.LocalFileExist)) {
                groupConfiguration.CreateFile();
                //groupConfiguration.Synchronize();
            }
        }

        #endregion

    }
}
